package com.tengju.bff.interfaces.covercharge.controller.portal;

import com.idanchuang.component.redis.util.DRedisLocks;
import com.tengju.bff.interfaces.covercharge.constant.BizConstants;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeErrorCode;
import com.tengju.bff.interfaces.covercharge.constant.IdentityTypeEnum;
import com.tengju.bff.interfaces.covercharge.constant.SelfCertificationTypeEnum;
import com.tengju.bff.interfaces.covercharge.controller.portal.assembler.SelfCertificationAssembler;
import com.tengju.bff.interfaces.covercharge.entity.po.ServiceSelfCertification;
import com.tengju.bff.interfaces.covercharge.entity.vo.SelfCertificationQuery;
import com.tengju.bff.interfaces.covercharge.entity.vo.SmsVerificationReq;
import com.tengju.bff.interfaces.covercharge.entity.vo.SmsVerificationV2Req;
import com.tengju.bff.interfaces.covercharge.entity.vo.SmsVerificationVerifyReq;
import com.tengju.bff.interfaces.covercharge.service.SelfCertificationService;
import com.tengju.bff.interfaces.covercharge.util.UserUtils;
import com.tengju.bff.interfaces.covercharge.util.regularUtils;
import com.tengju.bff.interfaces.shared.ApiResponse;
import com.tengju.data.domain.shared.JsonUtil;
import com.tengju.user.domain.model.archive.sign.SignFromEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@Slf4j
@RequestMapping("/api/selfCertification")
@Api(value = "selfCertification", tags = "自认证个人/企业")
public class SelfCertificationController {
    @Autowired
    private SelfCertificationService selfCertificationService;

    @PostMapping("/registered")
    @ResponseBody
    @ApiOperation(value = "注册成为自认证个人/企业")
    public ApiResponse<?> registered(HttpServletRequest request, @RequestBody SelfCertificationQuery selfCertificationQuery) {

        log.info("注册成为自认证个人/企业,selfCertificationQuery：{}", JsonUtil.toJSONString(selfCertificationQuery));

        selfCertificationQuery.setFrom(UserUtils.getPlatFrom(request));
        Integer idCode = UserUtils.getIdCode(request);
        selfCertificationQuery.setIdCode(idCode);

        Assert.notNull(selfCertificationQuery.getIsRule(), "查询类型不能为空");
        Assert.notNull(selfCertificationQuery.getType(), "认证类型不能为空");
        Assert.isTrue((!selfCertificationQuery.getType().equals(SelfCertificationTypeEnum.COMPANY.getCode()) || !selfCertificationQuery.getType().equals(SelfCertificationTypeEnum.SINGLE.getCode())), "认证类型不对");

        //公共判断
        Assert.notNull(selfCertificationQuery.getIdCode(), "代理IdCode不能为空");
        Assert.notNull(selfCertificationQuery.getCompanyTel(), "联系方式不能为空");
        Assert.notNull(selfCertificationQuery.getCompanyNo(), "社会信用代码不能为空");
        Assert.isTrue(regularUtils.numTheLetter(selfCertificationQuery.getCompanyNo()), "社会信用代码不是大小写字母或数字组成");
        // todo 删除开户信息校验 (DaMu)
        Assert.notNull(selfCertificationQuery.getBusinessImgId(), "请上传营业执照");
        Assert.notNull(selfCertificationQuery.getIdcardName(), "法人姓名不能为空");
        Assert.notNull(selfCertificationQuery.getLegalMobile(), "法人手机号不能为空");
        Assert.isTrue(regularUtils.isNum(selfCertificationQuery.getLegalMobile()), "法人手机号必须是数字");
        Assert.notNull(selfCertificationQuery.getIdcardNo(), "法人身份证号不能为空");
        Assert.isTrue(regularUtils.numTheLetter(selfCertificationQuery.getIdcardNo()), "法人身份证号不是大小写字母或数字组成");

        // 默认身份证
        if (StringUtils.isEmpty(selfCertificationQuery.getIdcardType())){
            selfCertificationQuery.setIdcardType(IdentityTypeEnum.TYPE_0.getType());
        }
        if (selfCertificationQuery.getType().equals(SelfCertificationTypeEnum.COMPANY.getCode())) {
            Assert.notNull(selfCertificationQuery.getLicenceImgId(), "请上传开户许可证图片");
            Assert.notNull(selfCertificationQuery.getCompanyName(), "企业名称不能为空");
            Assert.isTrue(regularUtils.specialCharacters(selfCertificationQuery.getCompanyName()), "企业名称包含特殊字符");
            Assert.notNull(selfCertificationQuery.getCompanyAddress(), "企业地址不能为空");
            // 如果是港澳台身份证
            if (IdentityTypeEnum.TYPE_B.getType().equals(selfCertificationQuery.getIdcardType())
                    || IdentityTypeEnum.TYPE_C.getType().equals(selfCertificationQuery.getIdcardType())) {
                Assert.notNull(selfCertificationQuery.getIdcardUpId(), "请上传身份证正面");
                Assert.notNull(selfCertificationQuery.getIdcardDownId(), "请上传身份证反面");
            }
        } else {//个体工商户
            Assert.notNull(selfCertificationQuery.getCompanyName(), "经营名称不能为空");
            Assert.isTrue(regularUtils.specialCharacters(selfCertificationQuery.getCompanyName()), "经营名称包含特殊字符");
            Assert.notNull(selfCertificationQuery.getCompanyAddress(), "经营地址不能为空");
            Assert.notNull(selfCertificationQuery.getIdcardUpId(), "请上传身份证正面");
            Assert.notNull(selfCertificationQuery.getIdcardDownId(), "请上传身份证反面");
            selfCertificationQuery.setLicenceImgId(selfCertificationQuery.getBusinessImgId());
        }

        return DRedisLocks.runWithLock(BizConstants.SELF_CERTIFICATION_REGISTERED + idCode, 500, () -> {
            try {
                selfCertificationService.registered(selfCertificationQuery);
                return ApiResponse.newSuccess();
            } catch (Exception e) {
                log.error("自认证注册报错", e);
                return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
            }
        });
    }

    @PostMapping("/registeredInfo")
    @ResponseBody
    @ApiOperation(value = "查询自认证信息")
    public ApiResponse<ServiceSelfCertification> companyApplyInfo(HttpServletRequest request, @RequestBody SelfCertificationQuery selfCertificationQuery) {
        try {
            selfCertificationQuery.setFrom(UserUtils.getPlatFrom(request));
            Integer idCode = UserUtils.getIdCode(request);
            selfCertificationQuery.setIdCode(idCode);
            Assert.notNull(selfCertificationQuery.getIdCode(), "代理IdCode不能为空");
            ServiceSelfCertification certificationWithdraw = selfCertificationService.registeredInfo(selfCertificationQuery);
            return ApiResponse.newSuccess(certificationWithdraw);
        } catch (Exception e) {
            log.error("查询自认证信息报错", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }

    @PostMapping("/registeredUpgrade")
    @ResponseBody
    @ApiOperation(value = "区域服务商判断需不需要升级")
    public ApiResponse<?> registeredUpgrade(HttpServletRequest request, @RequestBody SelfCertificationQuery selfCertificationQuery) {
        try {
            selfCertificationQuery.setFrom(UserUtils.getPlatFrom(request));
            Integer idCode = UserUtils.getIdCode(request);
            selfCertificationQuery.setIdCode(idCode);
            Assert.notNull(selfCertificationQuery.getIdCode(), "代理IdCode不能为空");
            Assert.notNull(selfCertificationQuery.getFromType(), "来源不能为空");
            Integer registeredUpgradeStatus = selfCertificationService.registeredUpgrade(selfCertificationQuery);
            return ApiResponse.newSuccess(registeredUpgradeStatus);
        } catch (Exception e) {
            log.error("区域服务商判断需不需要升级报错", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }

    @PostMapping("/doIdentity3Auth")
    @ResponseBody
    @ApiOperation(value = "手机三要素获取验证码")
    public ApiResponse<?> doIdentity3Auth(HttpServletRequest request, @RequestBody SmsVerificationReq smsVerificationReq) {
        log.info("手机三要素获取验证码参数:{}", JsonUtil.toJSONString(smsVerificationReq));
        try {
            Assert.notNull(smsVerificationReq.getName(), "姓名不能为空");
            Assert.notNull(smsVerificationReq.getIdCardType(), "身份证类型不能为空");
            Assert.notNull(smsVerificationReq.getIdCardNo(), "身份证号不能为空");
            Assert.notNull(smsVerificationReq.getMobile(), "手机号码不能为空");
            String personalIdentity3Key = selfCertificationService
                    .doIdentity3Auth(SelfCertificationAssembler.dtoToModel(smsVerificationReq), false);
            return ApiResponse.newSuccess(personalIdentity3Key);
        } catch (Exception e) {
            log.error("手机三要素获取验证码报错", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }

    @PostMapping("/v2/doIdentity3Auth")
    @ResponseBody
    @ApiOperation(value = "手机三要素获取验证码v2")
    public ApiResponse<?> doIdentity3AuthV2(@RequestBody SmsVerificationV2Req smsVerificationV2Req) {
        log.info("手机三要素获取验证码参数:{}", smsVerificationV2Req);
        try {
            String personalIdentity3Key = selfCertificationService
                    .doIdentity3Auth(SelfCertificationAssembler.dtoToModel(smsVerificationV2Req), true);
            return ApiResponse.newSuccess(personalIdentity3Key);
        } catch (Exception e) {
            log.error("手机三要素获取验证码报错", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }

    @PostMapping("/doIdentity3AuthVerify")
    @ResponseBody
    @ApiOperation(value = "个人手机号三要素校验")
    public ApiResponse<?> doIdentity3AuthVerify(HttpServletRequest request, @RequestBody SmsVerificationVerifyReq smsVerificationVerifyReq) {
        log.info("个人手机号三要素校验：{}", smsVerificationVerifyReq.toString());
        try {
            Assert.notNull(smsVerificationVerifyReq.getPersonalIdentity3Key(), "验证的key不能为空");
            Assert.notNull(smsVerificationVerifyReq.getVcode(), "手机验证码不能为空");
            selfCertificationService.doIdentity3AuthVerify(smsVerificationVerifyReq);
            return ApiResponse.newSuccess();
        } catch (Exception e) {
            log.error("个人手机号三要素校验报错", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }

    @PostMapping("/noticeStarService")
    @ResponseBody
    @ApiOperation(value = "通知会员认证成功")
    public ApiResponse<?> noticeStarService(HttpServletRequest request, @RequestBody SelfCertificationQuery selfCertificationQuery) {
        try {
            selfCertificationQuery.setFrom(UserUtils.getPlatFrom(request));
            Integer idCode = UserUtils.getIdCode(request);
            selfCertificationQuery.setIdCode(idCode);
            Assert.notNull(selfCertificationQuery.getIdCode(), "代理IdCode不能为空");
            Assert.notNull(selfCertificationQuery.getFromType(), "来源不能为空");
            /*Assert.isTrue(selfCertificationQuery.getFromType()!=SignFromEnum.SERVICE_FEE.getCode(),"不是来自服务费认证");*/
            Assert.isTrue(!SignFromEnum.SERVICE_FEE.getCode().equals(selfCertificationQuery.getFromType()), "不是来自服务费认证");
            Boolean returnData = selfCertificationService.noticeStarService(selfCertificationQuery);
            return ApiResponse.newSuccess(returnData);
        } catch (Exception e) {
            log.error("通知会员认证成功报错", e);
            return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
        }
    }
}
